package jeesample.service.publishers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

import jeesample.dtos.BookingDTO;
import jeesample.dtos.RoomDTO;
import jeesample.model.Booking;
import jeesample.model.Room;
import jeesample.service.RoomBookingService;
import jeesample.service.RoomLocatorService;
import jeesample.service.impl.RoomBookingImpl;
import jeesample.service.impl.RoomLocatorImpl;

import org.apache.log4j.Logger;

public class BookingServicePublisher extends BaseServicePublisher {
	private Logger logger = Logger.getLogger(getClass());

	@Override
	protected Logger logger() {
		return logger;
	}

	private RoomBookingService roomBookingService = new RoomBookingImpl();
	private RoomLocatorService roomLocatorService = new RoomLocatorImpl();

	public List<BookingDTO> listBookedRooms() {
		dbg("listBookedRooms()");
		List<Booking> bookings = roomBookingService.getRoomsBooked();
		List<BookingDTO> dtos = new LinkedList<>();
		for (Booking booking : bookings) {
			BookingDTO dto = new BookingDTO(booking);
			dtos.add(dto);
		}
		return dtos;
	}

	public List<RoomDTO> listAvailableRooms() {
		dbg("listAvailableRooms()");
		List<Room> rooms = roomBookingService.getRoomsAvailable();
		List<RoomDTO> dtos = new LinkedList<>();
		for (Room room : rooms) {
			RoomDTO dto = new RoomDTO(room);
			dtos.add(dto);
		}
		return dtos;
	}

	public BookingDTO reserve(final BookingDTO dto) {
		dbg("reserve(" + dto.getRoomId() + "," + dto.getBookingId() + ","
				+ dto.getBookedBy() + "," + dto.getStartTime() + ","
				+ dto.getEndTime() + ")");
		Booking booking = new Booking();
		booking.setRoomId(dto.getRoomId());
		booking.setBookingId(dto.getBookingId());

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			booking.setStartTime(df.parse(dto.getStartTime()));
		} catch (ParseException e) {
			err("Failure to parse startTime to Date Object:", e);
		}
		try {
			booking.setEndTime(df.parse(dto.getEndTime()));
		} catch (ParseException e) {
			err("Failure to parse endTime to Date Object:", e);
		}
		booking.setBookedBy(dto.getBookedBy());

		booking = roomBookingService.reserve(booking);

		BookingDTO dtoReply = new BookingDTO();
		dtoReply.setBookedBy(booking.getBookedBy());
		dtoReply.setBookingId(booking.getBookingId());
		dtoReply.setRoomId(booking.getRoomId());
		dtoReply.setStartTime(dto.getStartTime());
		dtoReply.setEndTime(dto.getEndTime());
		return dto;
	}

	public RoomDTO unreserve(final String bookingId) {
		dbg("unreserve(" + bookingId + ")");
		Booking booking = new Booking();
		booking.setBookingId(bookingId);
		Room room = roomBookingService.unreserve(booking);
		RoomDTO dto = new RoomDTO(room);
		return dto;
	}

}
